package com.example.coolshark.filtter;

import com.example.coolshark.pojo.vo.UserVO;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @Name: MyFilter
 * @Author: 西风残叶
 * @Company: 朝兮网络工作室
 * @Data: 2023/11/27 22:29
 */
// 配置请求是的页面进行过滤
@WebFilter(filterName = "MyFilter",
        urlPatterns = {"/insertProduct.html", "/insertBanner.html",
                "/admin.html","/product/delete"})
public class MyFilter implements Filter {
    // 过滤器初始化方法
    public void init(FilterConfig filterConfig) throws ServletException {
    }
// 请求资源之前和之后执行的放哪发
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        // 因为要用到子类类型中的方法,所以进行类型强转
        HttpServletRequest req= (HttpServletRequest) servletRequest;
        HttpServletResponse res  = (HttpServletResponse) servletResponse;
        // 从请求中对象中获取当前客户端对应的会话对象
        HttpSession session = req.getSession();
        // 从绘画对象中获取登录成功时保存的用户对象
        UserVO user = (UserVO) session.getAttribute("user");
        // 判断是否登录过
        if (user!=null){// 允许客户端请求资源
            chain.doFilter(servletRequest, servletResponse);
        }else { // 未登录过,禁止请求资源,并显示登录页面
            res.sendRedirect("/login.html");
        }
        System.out.println("过滤器执行了!");
        // chain.doFilter(servletRequest, servletResponse);
    }

    // 过滤器销毁方法
    public void destroy() {
    }
}
